package io.inputstream;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class fileInputStream {
    public static void main(String[] args) throws IOException {
        fileInputStream stream = new fileInputStream();
        stream.cope();
    }


    public void read() throws IOException {
        String path = "d:/Test/create1.txt";
        java.io.FileInputStream inputStream = null;
        int readData = 0;
        byte[] bytes = new byte[1024];
        try {
            //inputStream.read()一次读一个字节
            //inputStream.read(bytes)返回读取到的总字节数
            inputStream = new java.io.FileInputStream(path);
            while ((readData=inputStream.read(bytes)) != -1){
                System.out.print(new String(bytes,0,readData));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            inputStream.close();
        }
    }
    public void write(){
        String path = "d:/Test/create1.txt";
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(path,true);//true追加写入
            String s= "aaaa";
            byte[] bytes = s.getBytes();
            outputStream.write(bytes);//每次写入会覆盖原来的内容
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public void cope(){
        String source = "d:/Test/create1.txt";
        String target = "d:/Test/create2.txt";
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        int readData = 0;
        try {
            fileInputStream = new FileInputStream(source);
            fileOutputStream = new FileOutputStream(target,true);
            byte[] bytes = new byte[1024];
            while ((readData=fileInputStream.read(bytes)) !=-1){
                fileOutputStream.write(bytes,0,readData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (fileInputStream!=null) fileOutputStream.close();
                if (fileInputStream!=null) fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
